package com.zyc.demo.v.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

/**
 * @author: zyc
 */
@RestController
public class UploadController {


    @RequestMapping("/upload")
    public Object upload(MultipartHttpServletRequest request) throws IOException {
        Iterator<String> iterator  = request.getFileNames();
        final String     filesRoot = "D:/Tools/IdeaIU/IdeaProjects2/demo-v/files";
        while (iterator.hasNext()) {
            String fn = iterator.next();

            List<MultipartFile> multipartFileList = request.getFiles(fn);
            for (MultipartFile multipartFile : multipartFileList) {
                // 原文件名称
                String originalFilename = multipartFile.getOriginalFilename();

                int    idx    = originalFilename.indexOf(".");
                String suffix = "";
                if (idx != -1) {
                    suffix = originalFilename.substring(idx);
                }
                String save2Path = filesRoot + "/" + UUID.randomUUID().toString() + suffix;
                multipartFile.transferTo(Paths.get(save2Path));
            }
        }
        return "成功";
    }

    // 文件名去除特殊符号
    private String replaceSpecialSymbolsForFilename(String filename) {
        return replaceSpecialSymbolsForFilename(filename, "");
    }

    private String replaceSpecialSymbolsForFilename(String filename, String replacement) {
        @SuppressWarnings("ALL")
        String regex = "[\\\\/:\\*\\?\"<>|]";
        return filename.replaceAll(regex, replacement);
    }
}
